/**
 * @Author:  renyc
 * @Date: 2023年2月9日10:14:55
 */
'use strict';

import * as Cesium from "cesium/Cesium";
import FeatureSource from "./FeatureSource";
import CsvProvider from "../../provider/vector/CsvProvider";
import SourceType from "../../type/SourceType";
import {SourceEventType} from "../../../event/EventType";

/**
 * @description
 * options = {
        url: url, 
        header : true,
        fields :  {
            x : "X",
            y : "Y"
        }
 */
class CsvSource extends FeatureSource {
    constructor(name, options){

        if(!options){
            throw new Error('CsvSource: options无效');
        }
        if(!options.url){
            throw new Error('CsvSource: url为空');
        }

        super(name, options); 

        //this._url = options.url;

        this._type = SourceType.CSV;
        this._provider = new CsvProvider();       
        
        // this._delegate = null;
        // this._cesiumGeoJsonDataSource = new Cesium.GeoJsonDataSource(name);
    }

    /**
     * Source获取数据
     * @override
     * @description
     *  fetch函数有Source的派生类实现。
     * @returns
     *  success:    触发FETCHED事件。调用者响应FETCHED事件获得数据。 
     *  failure:    触发FETCH_ERROR事件 
     * 
     */
    fetch(){
        let that = this;

        let provider = this._provider;

        fetch(this._url)
        .then(resp=>{
            if(resp.status!== 200){
                //触发FETCH_ERROR事件
                this._fire(SourceEventType.FETCH_ERROR, { 
                    message: resp.statusText
                });
                return;
            }
            else{
                return resp.text();
            }            
        })
        .then(text => {
            let provider = this._provider;
            let json = provider.parseGeoJson(text);

            that._json = json;
            //触发数据获取的FETCHED事件
            that._fire(SourceEventType.FETCHED, { 
                json : json,            
                source : that,
                // format : DataFormat.GEOJSON,
                // datasetName : typeName
            });


            //that._delegate = that._cesiumGeoJsonDataSource.load(json);
            // that._fire(SourceEventType.FETCHED, { 
            //     json : json,
            //     data: that._delegate,                
            //     source : that,
            //     // format : DataFormat.GEOJSON,
            //     // datasetName : typeName
            // });
        })
        .catch(err=>{
            //触发FETCH_ERROR事件
            this._fire(SourceEventType.FETCH_ERROR, { 
                message: err
            });
        });
    }

    /**
     * @description 清空Source
     * @override
     */
    cleanup(){

    }

    // /**
    //  * @description 获取json对象
    //  */
    // get json(){
    //     return this._json;
    // }

}

export default CsvSource;
